package com.cicc.wm.lock.jdbc;

import cn.hutool.extra.spring.SpringUtil;
import com.cicc.wm.lock.DistributedLock;
import com.cicc.wm.lock.LockRegistry;
import com.cicc.wm.lock.LockRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.Ordered;
import org.springframework.util.Assert;

import javax.sql.DataSource;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * jdbc锁注册中心
 */
@Slf4j
public class JdbcLockRegistry implements LockRegistry, Ordered {
    /**
     * 存储锁信息
     */
    private final Map<String, DistributedLock> locks = new ConcurrentHashMap<>();

    private final LockRepository client;

    public JdbcLockRegistry(LockRepository client) {
        Assert.notNull(client, "'client' must not be null");
        this.client = client;
    }

    @Override
    public DistributedLock obtain(String lockKey) {
        return this.locks.computeIfAbsent(lockKey, (key) -> new JdbcDistributedLock(this.client, key));
    }

    @Override
    public boolean isActive() {
        // jdbc是分布式锁兜底方案
        return SpringUtil.getBean(DataSource.class) != null;
    }

    @Override
    public int getOrder() {
        return 20;
    }
}
